package me.khrystal.rxnews.base;

import android.content.Context;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;

import com.socks.library.KLog;

import java.util.ArrayList;
import java.util.List;

import me.khrystal.rxnews.R;
import me.khrystal.rxnews.callback.OnItemClickListener;

/**
 * usage: Recycler通用适配器
 * author: kHRYSTAL
 * create time: 16/4/8
 * update time:
 * email: 723526676@qq.com
 */
public abstract class BaseRecyclerAdapter<T> extends RecyclerView.Adapter<BaseRecyclerViewHolder>{

    public static final int TYPE_HEADER = 1;
    public static final int TYPE_ITEM = 2;
    public static final int TYPE_FOOTER = 3;

    protected List<T> mData;
    protected Context mContext;
    protected boolean mUseAnimation;
    protected LayoutInflater mInflater;
    protected OnItemClickListener mClickListener;
    protected boolean mShowFooter;

    private RecyclerView.LayoutManager mLayoutManager;
//    用于执行itemView动画 只执行一次 再次bindview的时候不再执行
    private int mLastPosition = -1;

    public BaseRecyclerAdapter(Context context,List<T> data){
        this(context,data,true);
    }

    public BaseRecyclerAdapter(Context context,List<T> data,boolean useAnimation){
        this(context,data,useAnimation,null);
    }

    public BaseRecyclerAdapter(Context context,List<T> data,boolean useAnimation,RecyclerView.LayoutManager layoutManager){
        mContext = context;
        mUseAnimation = useAnimation;
        mData = data == null ? new ArrayList<T>() : data;
        mInflater = LayoutInflater.from(context);
    }


    @Override
    public BaseRecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == TYPE_FOOTER){
            return new BaseRecyclerViewHolder(mContext,mInflater.inflate(R.layout.item_footer
                    ,parent,false));
        }else {
            final BaseRecyclerViewHolder holder = new BaseRecyclerViewHolder(mContext,
                    mInflater.inflate(getItemLayoutId(viewType),parent,false));
            if (mClickListener != null){
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mClickListener.onItemClick(v,holder.getLayoutPosition());
                    }
                });
            }
            return holder;
        }
    }

    @Override
    public void onBindViewHolder(BaseRecyclerViewHolder holder, int position) {
        if (getItemViewType(position)==TYPE_FOOTER){
            if (mLayoutManager != null){
                if (mLayoutManager instanceof StaggeredGridLayoutManager){
                    if (((StaggeredGridLayoutManager)mLayoutManager).getSpanCount()!=1){
                        StaggeredGridLayoutManager.LayoutParams params =
                                (StaggeredGridLayoutManager.LayoutParams)holder.itemView.getLayoutParams();
//                        TODO 设置当前itemView 占满一行
                        params.setFullSpan(true);
                    }
                }else if (mLayoutManager instanceof GridLayoutManager){
                    if (((GridLayoutManager)mLayoutManager).getSpanCount()!=1
                            &&((GridLayoutManager)mLayoutManager).getSpanSizeLookup() instanceof GridLayoutManager.DefaultSpanSizeLookup){
                        throw new RuntimeException("网格布局列数大于1时应该继承SpanSizeLookup时处理底部加载时布局占满一行");
                    }
                }
            }
            holder.getPacman(R.id.pac_man).performLoading();
        }else {
            bindData(holder,position,mData.get(position));
            if (mUseAnimation)
                setAnimation(holder.itemView,position);
        }
    }

    protected void setAnimation(View viewToAnimate,int position){
        if (position > mLastPosition){
            Animation animation = AnimationUtils
                    .loadAnimation(viewToAnimate.getContext(),R.anim.item_bottom_in);
            viewToAnimate.startAnimation(animation);
            mLastPosition = position;
        }
    }

    /**
     * 从屏幕滑走 移除动画
     * @param holder
     */
    @Override
    public void onViewDetachedFromWindow(BaseRecyclerViewHolder holder) {
        super.onViewDetachedFromWindow(holder);
        if (mUseAnimation && holder.itemView.getAnimation() != null
                && holder.itemView.getAnimation().hasStarted()){
            holder.itemView.clearAnimation();
        }
    }

    /**
     * 需要判断是否有footer footer是通过type加入的 所以如果存在正在显示的footer
     * 那么item的个数应该为list.size＋1
     * @return
     */
    @Override
    public int getItemCount() {
        int i = mShowFooter ? 1: 0;
        return  mData != null ? mData.size() + i : 0;
    }

    @Override
    public int getItemViewType(int position) {
        if (mShowFooter && getItemCount()-1 == position){
            return TYPE_FOOTER;
        }
        return bindViewType(position);
    }

    public void add(int pos , T item){
        mData.add(pos,item);
        notifyItemChanged(pos);
    }

    public void delete(int pos){
        mData.remove(pos);
        notifyItemRemoved(pos);
    }

    public void addMoreData(List<T> data){
        int startPos =  mData.size();
        mData.addAll(data);
        notifyItemRangeInserted(startPos,data.size());
    }

    public List<T> getData(){
        return  mData;
    }

    public void setData(List<T> data){
        mData = data;
        notifyDataSetChanged();
    }

    public void setOnItemClickListener(OnItemClickListener listener){
        mClickListener = listener;
    }

    public abstract int getItemLayoutId(int viewType);

    public abstract void bindData(BaseRecyclerViewHolder holder,int position,T item);

    protected int bindViewType(int position){
        return 0;
    }

    public void showFooter(){
        KLog.e("Adapter显示尾部:" + getItemCount());
        notifyItemInserted(getItemCount());
        mShowFooter = true;
    }

    public void hideFooter(){
        KLog.e("Adapter隐藏尾部:" + (getItemCount()-1));
        notifyItemRemoved(getItemCount() - 1);
        mShowFooter = false;
    }
}
